<?php
namespace Auth;

/**
 * @brief Jwt Token类
 */
class Jwt {
    /**
     * 生成token
     *
     * @param $guid //用户ID
     * 
     * @return mixed
     */
    public static function getToken($guid) {
        $config = \Yaf_Registry::get('Config');
        $expire = $config->auth->jwt->expire;
        $nowtime = time();
        $token = [
            "iss" => 'Server',       //签发人
            "aud" => 'App',          //受众
            "iat" => $nowtime,       //签发时间
            "nbf" => $nowtime + 0,   //生效时间
            'exp' => $nowtime + $expire, //过期时间
            'guid' => $guid  //自定义参数，用户ID
        ];

        // encode
        $jwt = \Jwt::encode($token, $config->auth->jwt->key, 'HS256'); //默认就是 'HS256'

        return $jwt;
    }

    /**
     * 解密token
     *
     * @param $jwt
     * 
     * @return mixed
     */
    public static function checkToken($jwt) {
        // decode
        $res = \Jwt::decode($jwt, \Yaf_Registry::get('Config')->auth->jwt->key, ['HS256']);
        $res = $res ? json_decode(json_encode($res), true) : [];
        return $res['guid'] ?? 0;
    }
}
